package com.geeksx.trainer.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geeksx.trainer.common.PageRequest;
import com.geeksx.trainer.common.PageResult;
import com.geeksx.trainer.common.api.Result;
import com.geeksx.trainer.entity.KnowledgeCategory;
import com.geeksx.trainer.service.KnowledgeCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 知识分类 Controller
 * 提供分类的增删改查接口
 */
@RestController
@RequestMapping("/api/categories")
public class KnowledgeCategoryController {

    @Autowired
    private KnowledgeCategoryService categoryService;

    /**
     * 分页获取分类列表，支持模糊搜索和按父ID过滤
     *
     * @param pageRequest 分页请求
     * @param name 分类名称（模糊搜索）
     * @param parentId 父分类ID（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    public Result<PageResult<KnowledgeCategory>> getCategoryPage(
            PageRequest pageRequest,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long parentId) {
        // 构建分页对象
        Page<KnowledgeCategory> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());

        // 构建查询条件
        LambdaQueryWrapper<KnowledgeCategory> wrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            wrapper.like(KnowledgeCategory::getName, name.trim());
        }
        if (parentId != null) {
            wrapper.eq(KnowledgeCategory::getParentId, parentId);
        }
        wrapper.orderByAsc(KnowledgeCategory::getSort);

        // 查询分页数据
        Page<KnowledgeCategory> resultPage = categoryService.page(page, wrapper);

        return Result.success(PageResult.of(resultPage));
    }

    /**
     * 获取分类列表（可带查询条件）
     */
    @GetMapping("/list")
    public Result<List<KnowledgeCategory>>  listCategories(@RequestParam(required = false) Long parentId,
                                                           @RequestParam(required = false)Integer level) {
        QueryWrapper<KnowledgeCategory> wrapper = new QueryWrapper<>();

        wrapper.eq(level != null,"level", level);
        wrapper.eq(parentId != null,"parent_id", parentId);
        wrapper.orderByAsc("sort");
        return Result.success(categoryService.list(wrapper));
    }

    /**
     * 获取分类树形结构
     */
    @GetMapping("/tree")
    public Result<List<Map<String, Object>>> getCategoryTree(Long parentId) {
        List<KnowledgeCategory> all = new ArrayList<>();
        all.add(KnowledgeCategory.builder().id(0L).name("根节点").level(0).sort(0).build());
        all.addAll(categoryService.list(new QueryWrapper<KnowledgeCategory>().orderByAsc("sort")));
        return Result.success(buildTree(all, parentId));
    }

    /**
     * 递归构建树
     */
    private List<Map<String, Object>> buildTree(List<KnowledgeCategory> all, Long parentId) {
        return all.stream()
                .filter(c -> Objects.equals(c.getParentId(), parentId))
                .map(c -> {
                    Map<String, Object> node = new HashMap<>();
                    node.put("id", c.getId());
                    node.put("name", c.getName());
                    node.put("description", c.getDescription());
                    node.put("level", c.getLevel());
                    node.put("sort", c.getSort());
                    node.put("children", buildTree(all, c.getId()));
                    return node;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取分类详情
     */
    @GetMapping("/{id}")
    public Result<KnowledgeCategory> getCategoryDetail(@PathVariable Long id) {
        return Result.success(categoryService.getById(id));
    }

    /**
     * 新增分类
     */
    @PostMapping
    public Result<Boolean> createCategory(@RequestBody KnowledgeCategory category) {
        return Result.success(categoryService.save(category));
    }

    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateCategory(@PathVariable Long id, @RequestBody KnowledgeCategory category) {
        category.setId(id);
        return Result.success(categoryService.updateById(category));
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCategory(@PathVariable Long id) {
        return Result.success(categoryService.deleteCategory(id));
    }

    /**
     * 批量删除分类
     */
    @DeleteMapping("/batch-delete")
    public boolean batchDeleteCategories(@RequestBody Map<String, List<Long>> request) {
        List<Long> ids = request.get("ids");
        return categoryService.removeByIds(ids);
    }

    /**
     * 更新分类排序
     * 前端传入 JSON 数组: [{ "id": 1, "sort": 1 }, { "id": 2, "sort": 2 }]
     */
    @PutMapping("/sort")
    public boolean updateCategorySort(@RequestBody List<Map<String, Object>> sortList) {
        List<KnowledgeCategory> categories = sortList.stream().map(item -> {
            KnowledgeCategory c = new KnowledgeCategory();
            c.setId(Long.valueOf(item.get("id").toString()));
            c.setSort(Integer.valueOf(item.get("sort").toString()));
            return c;
        }).collect(Collectors.toList());

        return categoryService.updateBatchById(categories);
    }
}
